<?php

namespace App\Http\Controllers\Mobile;

use App\Models\Item;
use App\Models\ItemCatlog;

class CatlogController extends BaseController
{
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function index()
    {
        $this->assign(['catlogs'=>ItemCatlog::fetchWithCache()]);
        return $this->view('mobile.item.catlog');
    }

    public function itemlist($catid)
    {
        $this->assign([
            'catid'=>$catid,
            'catlog'=>ItemCatlog::find($catid)
        ]);

        return $this->view('mobile.item.list');
    }

    public function getJson()
    {
        $offset = $this->request->input('offset');
        $count  = $this->request->input('count');
        $offset = $offset ? $offset : 0;
        $count  = $count ? $count : 20;

        $query = Item::with(['shop'])->onSale();

        $keywords = $this->request->input('keywords');
        if ($keywords) {
            $query = $query->where('title', 'LIKE', "%$keywords%")->orWhereHas('shop', function ($query) use ($keywords){
                return $query->where('shop_name', 'LIKE', "%$keywords%");
            });
        }

        $catid = $this->request->input('catid');
        if ($catid) {
            $catIds = ItemCatlog::fetchAllChildIds($catid);
            $query = $query->whereIn('catid', $catIds);
        };

        $shop_id = $this->request->input('shop_id');
        if ($shop_id) $query = $query->where('shop_id', $shop_id);

        $sort = $this->request->input('sort');
        if ($sort == 'sold-desc') {
            $query = $query->orderByDesc('sold');
        } elseif ($sort == 'rate-desc') {
            $query = $query->orderByDesc('reviews');
        } else {
            $query = $query->orderByDesc('itemid');
        }

        $items = $query->offset($offset)->limit($count)->get();
        return ajaxReturn([
            'total_count'=>$query->count(),
            'offset'=>$offset,
            'count'=>$items->count(),
            'items'=>$items->map(function ($item){
                $item->thumb = image_url($item->thumb);
                $item->image = image_url($item->image);
                if ($item->shop) {
                    $item->shop->logo = image_url($item->shop->logo);
                } else {
                    $item->shop = [];
                }
                $item->url = mobile_item_url($item->itemid);
                return $item;
            })
        ]);
    }
}
